/*
 *
 * @ProjectName:    my_umi_app
 * @Package:
 * @ClassName:      article_list
 * @Description:    文章列表
 * @Author:         SuPeiSen
 * @CreateDate:     2021/1/31 1:39 上午
 * @UpdateDate:     2021/1/31 1:39 上午
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */

import ProTable, { ProColumns } from '@ant-design/pro-table';
import {
  getCategoryByAdminApi,
  updateCategoryApi,
} from '@/service/category_api';
import { message, Tag, Switch } from 'antd';
import React from 'react';
import { ArticleListItemType } from '@/type/article_type';
import { SortOrder } from 'antd/lib/table/interface';
import { log, numberToBool, rgbaColorByString } from '@/utils/app_fun';
import {
  ArticleListByAdminApi,
  DeleteArticleByAdminApi,
  updateArticleStatusApi,
} from '@/service/article_api';
import { history } from '@@/core/history';
import { AppConfig, AppImageUrl } from '@/config/app_config';
import { DeleteModalWidget } from '@/widget/ModalWidget/modal_widget';

const columns: ProColumns<ArticleListItemType>[] = [
  {
    title: '文章id',
    dataIndex: 'id',
    key: 'id',
    search: false,
    editable: false,
  },
  {
    title: '文章名称',
    dataIndex: 'article_title',
    render: (dom, item) => {
      return <h4>{item.article_title}</h4>;
    },
  },
  {
    title: '状态',
    // dataIndex: 'article_title',
    render: (dom, item) => {
      return (
        <div>
          {item.article_status === 1 ? <Tag>上架</Tag> : <div />}
          {item.article_sticky === 1 ? <Tag>置顶</Tag> : <div />}
          {item.article_originate === 1 ? <Tag>原创</Tag> : <div />}
        </div>
      );
    },
  },
  {
    title: '文章分类',
    dataIndex: 'articleCategory',
    render: (dom, item) => {
      return <Tag color="volcano">{item.articleCategory.category_name}</Tag>;
    },
  },
  {
    title: '文章标签',
    dataIndex: 'articleTag',
    render: (dom, item) => {
      const Tags = item.articleTag.map((tag) => {
        return (
          <Tag key={tag.id} color={rgbaColorByString(tag.tag_color)}>
            {tag.tag_name}
          </Tag>
        );
      });
      return Tags;
    },
  },
  {
    title: '文章图片',
    dataIndex: 'article_image',
    render: (dom, item) => {
      return (
        <img
          alt={item.article_image}
          src={AppImageUrl(item.article_image)}
          width="150px"
        />
      );
    },
  },
  {
    title: '操作',
    valueType: 'option',
    render: (dom, record, _, action) => [
      <a
        key={'editable_' + `${record.id}`}
        onClick={(date) => {
          // @ts-ignore
          history.push({
            pathname: '/admin/article/update_article',
            query: {
              id: record.id,
              article_image:
                record.article_image ?? record.articleTag[0].icon_url,
            },
          });
        }}
      >
        编辑
      </a>,
      <a
        key={'preview_' + `${record.id}`}
        onClick={(date) => {
          // @ts-ignore
          history.push({
            pathname: '/admin/article/preview_article',
            query: {
              id: record.id,
            },
          });
        }}
      >
        预览
      </a>,
      <DeleteModalWidget
        key={'delete_' + `${record.id}`}
        onOk={() => {
          DeleteArticleByAdminApi(record.id).then((success) => {
            if (success) {
              message.success('删除成功');
              action?.reload();
            } else {
              message.error('删除失败');
            }
          });
        }}
        onCancel={() => {}}
      >
        <a>删除</a>
      </DeleteModalWidget>,
      <Switch
        key={record.id}
        checkedChildren="上架"
        unCheckedChildren="下架"
        defaultChecked={numberToBool(record.article_status)}
        onChange={async (checked, event) => {
          const success = await updateArticleStatusApi({
            id: record.id,
            status: checked,
          });
          if (success) {
            message.success('更新成功');
          } else {
            message.success('更新失败');
          }
        }}
      />,
    ],
  },
];

export default () => {
  const getMenuList = async (
    params: {
      pageSize?: number;
      current?: number;
      keyword?: string;
    },
    sort: {
      [key: string]: SortOrder;
    },
    filter: {
      [key: string]: React.ReactText[];
    },
  ) => {
    const model = await ArticleListByAdminApi({
      page: params.current ?? 1,
      limit: params.pageSize ?? 10,
    });
    if (model.success) {
      return {
        success: true,
        data: model.data!.data.lists,
        total: model.data!.data.total,
      };
    }
    return {
      data: [],
      success: false,
    };
  };

  return (
    <ProTable<ArticleListItemType>
      columns={columns}
      rowKey="id"
      // @ts-ignore
      request={getMenuList}
      editable={{
        onSave: async (key, row) => {
          const success = await updateCategoryApi(row);
          if (success) {
            message.success('成功');
          } else {
            message.error('失败');
          }
        },
      }}
      pagination={{ pageSize: 5 }}
    />
  );
};
